<template>
  <el-button
    class="bg-[var(--el-color-primary)]"
    type="primary"
    @click="sessionTimoutDialogRef.dialogVisible = true"
    >{{ $t('pageSessions.table.setting') }}</el-button
  >

  <session-timout-dialog ref="sessionTimoutDialogRef" />

  <div v-if="multipleSelection.length" class="w-full h-8 flex justify-end">
    <el-button @click="confirmDisconnectSessions()">
      {{ $t('pageSessions.action.disconnect') }}
    </el-button>
  </div>
  <el-table
    ref="tableRef"
    row-key="id"
    :data="TableData"
    @selection-change="handleSelectionChange"
    style="width: 100%"
  >
    <el-table-column type="selection" width="100" />
    <el-table-column
      prop="clientID"
      :label="$t('pageSessions.table.clientID')"
      width="300"
    />
    <el-table-column
      prop="username"
      :label="$t('pageSessions.table.username')"
      width="300"
    />
    <el-table-column
      prop="ipAddress"
      :label="$t('pageSessions.table.ipAddress')"
      width="300"
    />
    <el-table-column label="Operations">
      <template #header>
        <search-box
          ref="search"
          :placeholder="$t('pageSessions.table.searchSessions')"
          data-test-id="eventLogs-input-searchLogs"
        />
      </template>
      <template #default="scope">
        <el-button
          size="small"
          type="danger"
          class="bg-orange-600"
          @click="disconnect(scope.row.uri)"
          >{{ scope.row.actions[0].title }}</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <div class="demo-pagination-block mt-8">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="perPage"
      :page-sizes="[10, 20, 30, 40]"
      :small="false"
      :disabled="false"
      :background="true"
      layout="sizes, prev, pager, next"
      :total="allConnections.length"
    />
  </div>
</template>

<script setup lang="ts">
import { useSessionsStore } from '@/store/UserSecurity/Sessions/SessionsStore';
import SessionTimoutDialog from './SessionTimeoutDialog.vue';
import { useI18n } from 'vue-i18n';
import _ from 'lodash';

const sessionsStore = useSessionsStore();
const i18n = useI18n();

const search = ref();
const sessionTimoutDialogRef = ref();

const allConnections = computed(() => {
  const Connections = sessionsStore.allConnections.map((session: any[]) => {
    return {
      ...session,
      actions: [
        {
          value: 'disconnect',
          title: i18n.t('pageSessions.action.disconnect'),
        },
      ],
    };
  });
  filterConnections.value = _.cloneDeep(Connections);
  return Connections;
});

const filterConnections = ref([] as any[]);

const filterConnectionsComputed = computed(() => {
  if (search.value?.filter) {
    return filterConnections.value.filter((item) => {
      return _.includes(JSON.parse(JSON.stringify(item)), search.value.filter)
        ? true
        : false;
    });
  } else return filterConnections.value;
});

const TableData = computed(() => {
  const firstIndex = (currentPage.value - 1) * perPage.value;
  const lastIndex = currentPage.value * perPage.value;

  return filterConnectionsComputed.value.slice(firstIndex, lastIndex);
});

const perPage = ref(10);
const currentPage = ref(1);

const multipleSelection = ref([]);

const confirmDisconnectSessions = () => {
  ElMessageBox.confirm(
    i18n.t(
      'pageSessions.modal.disconnectMessage2',
      multipleSelection.value.length,
    ),
    i18n.t('pageSessions.modal.disconnectTitle'),
    {
      confirmButtonText: i18n.t('pageSessions.action.disconnect'),
      cancelButtonText: i18n.t('global.action.cancel'),
      type: 'warning',
    },
  )
    .then(() => {
      disconnectSessions(multipleSelection.value.map(({ uri }) => uri));
    })
    .catch(() => {});
};

const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
};

const disconnectSessions = (uris: any) => {
  sessionsStore.disconnectSessions(uris).then((messages: any) => {
    messages.forEach(({ type, message }: { type: string; message: string }) => {
      if (type === 'success') {
        ElNotification({
          title: 'Success',
          message,
          type: 'success',
        });
      } else if (type === 'error') {
        ElNotification({
          title: 'Error',
          message,
          type: 'error',
        });
      }
    });
  });
};

const disconnect = (uri: string) => {
  ElMessageBox.confirm(
    i18n.t('pageSessions.modal.disconnectMessage1'),
    i18n.t('pageSessions.modal.disconnectTitle'),
    {
      confirmButtonText: i18n.t('pageSessions.action.disconnect'),
      cancelButtonText: i18n.t('global.action.cancel'),
      type: 'warning',
    },
  )
    .then(() => {
      disconnectSessions([uri]);
    })
    .catch(() => {});
};
</script>
